
package cn.xabad.commons.plist;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;


public class PDict extends PListObject {

	
	private static final long serialVersionUID = -556589348083152733L;

	public static final String DOT = ".";
	protected Map<String, PListObject> configMap;

	public PDict() {
		configMap = new TreeMap<>();
		setType(PListObjectType.DICT);
	}

	
	public void putConfig(String key, PListObject value) {
		configMap.put(key, value);
	}

	
	
	public Map<String, PListObject> getConfigMap() {
		return configMap;
	}

	
	public void setConfigMap(Map<String, PListObject> configMap) {
		this.configMap = configMap;
	}

	
	@SuppressWarnings("unchecked")
	public <E extends PListObject> E getConfigurationObject(String key) {
		StringTokenizer st = new StringTokenizer(key, DOT);

		if (st.hasMoreTokens()) {
			Map<String, PListObject> dict = configMap;
			Object obj;
			while (st.hasMoreTokens()) {
				String token = st.nextToken();
				obj = dict.get(token);
				if (obj instanceof PDict) {
					dict = ((PDict) obj).getConfigMap();
					continue;
				}
				return (E) obj;
			}
		}
		return (E) configMap.get(key);
	}

	
	public PString getConfiguration(String key) {
		return (PString) getConfigurationObject(key);
	}

	
	public PString getConfigurationWithDefault(String key,
											   PString defaultValue) {
		PString value = getConfiguration(key);
		if (value == null) {
			return defaultValue;
		}

		return value;
	}

	
	public PInteger getConfigurationInteger(String key) {
		return (PInteger) getConfigurationObject(key);
	}

	
	public PInteger getConfigurationIntegerWithDefault(String key,
													   PInteger defaultValue) {
		PInteger value = getConfigurationInteger(key);
		if (value == null) {
			return defaultValue;
		}

		return value;
	}

	
	public PArray getConfigurationArray(String key) {
		return (PArray) getConfigurationObject(key);
	}

	
	@Override
	public String toString() {
		StringBuilder retVal = new StringBuilder();
		Set<String> keys = configMap.keySet();
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next();
			retVal.append("key=").append(key)
					.append(configMap.get(key).toString());
		}
		return retVal.toString();
	}

}
